import React, { Component } from "react";
import { shallowEqual } from "share/common";
class WrapFormItem extends Component {
  state = {
    value: {},
  };

  componentDidMount() {
    this.setValues(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (!shallowEqual(this.props.value, nextProps.value)) this.setValues(nextProps);
  }

  setValues = (props) => {
    if ("value" in props) {
      const value = props.value;
      const { parser } = props;
      this.setState({ value: parser(value) });
    }
  };

  onChange = () => {
    const { onChange, formatter } = this.props;
    const { value } = this.state;
    onChange && onChange(formatter(value));
  };

  dispatchOnChange = () => {
    this.onChange();
  };

  onChangeValue = (targetValue) => {
    let { value } = this.state;
    this.setState({ value: Object.assign({}, value, targetValue) }, this.dispatchOnChange);
  };

  render() {
    const { children } = this.props;
    const { value } = this.state;
    return children(this.onChangeValue, value);
  }

  static defaultProps = {
    formatter: (value) => value,
    parser: (value) => value || {},
  };
}

export default WrapFormItem;
